import { addElClass, removeArr, on, hasElClass } from "./util";

/**分页控件*/
export class PageCtl {
    /**
     * 构造
     * @param pageCtlTpl 模版元素
     * @param targetEl 输出到的元素
     * @param defPageSize 默认的一页几条
     * @param defPageNum 默认的第几页
     * @param defDataCount 默认的数据总数
    */
    constructor(pageCtlTpl, targetEl, defPageSize, defPageNum, defDataCount) {
        defPageSize = parseInt(defPageSize);
        defPageNum = parseInt(defPageNum);
        defPageNum = parseInt(defPageNum);
        if (!defPageSize || defPageSize < 1) defPageSize = 8;
        if (!defPageNum || defPageNum < 1) defPageNum = 1;

        this.currClass = pageCtlTpl.getAttribute('data-page-current-class');
        this.disabledClass = pageCtlTpl.getAttribute('data-page-disabled-class');
        this.targetEl = targetEl;
        this.pageSize = defPageSize;
        this.pageNum = defPageNum;
        this.dataCount = defDataCount;
        this.pageCount = parseInt((this.dataCount + this.pageSize - 1) / this.pageSize);//加一取整方式算页数
        this.events = [];


        this.targetEl.innerHTML = pageCtlTpl.innerHTML;
        this.ctlPagesizeSelect = this.targetEl.getElementsByClassName('page-ctl-pagesize-select')[0];
        this.ctlPrev = this.targetEl.getElementsByClassName('page-ctl-prev')[0];
        this.ctlPages = this.targetEl.getElementsByClassName('page-ctl-pages')[0];
        this.ctlPage = this.targetEl.getElementsByClassName('page-ctl-page')[0].cloneNode(true);
        this.ctlOmit = this.targetEl.getElementsByClassName('page-ctl-omit')[0].cloneNode(true);
        this.ctlNext = this.targetEl.getElementsByClassName('page-ctl-next')[0];
        this.ctlGo = this.targetEl.getElementsByClassName('page-ctl-go')[0];

        this.ctlPages.innerHTML = '';
        this.ctlPrev.setAttribute('data-page', 'prev');
        this.ctlNext.setAttribute('data-page', 'next');
        this.__setPageSizeSelect();

        this.renderPageCtl(this.pageSize, this.pageNum, this.dataCount);

        //注册事件
        on(this.ctlPagesizeSelect, ['change'], () => {
            this.pageSize = parseInt(this.ctlPagesizeSelect.options[this.ctlPagesizeSelect.selectedIndex].value);
            this.pageNum = 1;//页大小改变后,默认改成首页好了
            this.__emitCtlPage();
        });
        on(this.targetEl, ['click'], (ev) => {
            if (!ev.target) return;
            let p = ev.target.getAttribute('data-page');
            if (!p) return;
            if (!hasElClass(ev.target, this.disabledClass)) {
                //可点
                switch (p) {
                    case 'prev':
                        if (this.pageNum > 1) {
                            this.pageNum--;
                            this.__emitCtlPage();
                        }
                        break;
                    case 'next':
                        if (this.pageNum < this.pageCount) {
                            this.pageNum++;
                            this.__emitCtlPage();
                        }
                        break;
                    default:
                        var toPageNum = parseInt(p);
                        if (!isNaN(toPageNum) && toPageNum && toPageNum !== this.pageNum) {
                            this.pageNum = toPageNum;
                            this.__emitCtlPage();
                        }
                        break;
                }
            }
            ev.preventDefault();
            ev.stopPropagation();
            return false;
        });

        let goPageFn = () => {
            if (!this.ctlGo.value) {
                //没输入直接跳过
                return;
            }
            let toPageNum = parseInt(this.ctlGo.value);
            if (isNaN(toPageNum) || toPageNum < 1) {
                toPageNum = 1;
                this.ctlGo.value = toPageNum;
            } else if (toPageNum > this.pageCount) {
                toPageNum = this.pageCount;
                this.ctlGo.value = toPageNum;
            }
            //没变化,跳过
            if (toPageNum === this.pageNum) return;
            //触发
            this.pageNum = toPageNum;
            this.__emitCtlPage();

        };

        on(this.ctlGo, ['keydown'], (ev) => {
            //输入框回车提交
            if (ev.keyCode === 13) {
                goPageFn();
            }
        });
        on(this.ctlGo, ['change'], (ev) => {
            //离开焦点有变更提交
            goPageFn();
        });
        on(this.ctlGo, ['compositionend'], (ev) => {
            //移动端完成一次输入提交
            goPageFn();
        });
    }
    __renderPageOneCtl(pn) {
        let pageCtl = this.ctlPage.cloneNode(true);
        pageCtl.innerHTML = pn.toString();
        pageCtl.setAttribute('data-page', pn.toString());
        if (pn === this.pageNum) {
            addElClass(pageCtl, null, this.currClass);
        }
        this.ctlPages.appendChild(pageCtl);
    }
    __emitCtlPage() {
        for (let cb of this.events) {
            cb(this.pageSize, this.pageNum);
        }
    }
    __setPageSizeSelect(){
        let psStr = this.pageSize.toString();
        //页码选中
        for (let opt of this.ctlPagesizeSelect.options) {
            if (opt.value === psStr) {
                opt.selected = true;
            } else {
                opt.selected = false;
            }
        }
    }
    /**
     * 当用户在分页控制器上触发了分页(页大小,页面改变都会)
     * @params cb (pageSize, pageNum)
    */
    onCtlPage(cb) {
        this.events.push(cb);
    }
    offCtlPage(cb) {
        removeArr(this.events, c => c === cb);
    }
    /**
     * 数据加载完后,主动渲染分页控件
    */
    renderPageCtl(pageSize, pageNum, dataCount) {
        pageSize = parseInt(pageSize);
        pageNum = parseInt(pageNum);
        dataCount = parseInt(dataCount);
        if (this.pageSize !== pageSize) {
            this.__setPageSizeSelect();
        }
        this.pageSize = pageSize;
        this.pageCount = parseInt((dataCount + this.pageSize - 1) / this.pageSize);//加一取整方式算页数
        if (pageNum <= 1) {
            //首页,禁用上一页
            addElClass(this.ctlPrev, null, this.disabledClass);
        } else {
            addElClass(this.ctlPrev, this.disabledClass);
        }
        if (pageNum >= this.pageCount) {
            //尾页,禁用下一页
            addElClass(this.ctlNext, null, this.disabledClass);
        } else {
            addElClass(this.ctlNext, this.disabledClass);
        }

        //开始处理中间快捷页码
        this.ctlPages.innerHTML = '';
        let nextPn = 1, pn, end;
        //开始后3
        for (pn = nextPn; pn <= 2 && pn <= this.pageCount; pn++) {
            this.__renderPageOneCtl(pn);
        }
        nextPn = pn;

        //当前页前后各2
        pn = Math.max(this.pageNum - 1, nextPn);
        end = Math.min(this.pageNum + 1, this.pageCount);
        //发现是否有空隙,则插入省略号
        if (nextPn < pn) this.ctlPages.appendChild(this.ctlOmit.cloneNode(true));
        for (; pn <= end; pn++) {
            this.__renderPageOneCtl(pn);
        }
        nextPn = pn;


        //结束前3
        pn = Math.max(this.pageCount - 1, nextPn);
        end = this.pageCount;
        //发现是否有空隙,则插入省略号
        if (nextPn < pn) this.ctlPages.appendChild(this.ctlOmit.cloneNode(true));
        for (; pn <= end; pn++) {
            this.__renderPageOneCtl(pn);
        }

    }
}